<script setup>
import {
  Clock,
  Delete,
  Edit,
  Search,
  RefreshRight,
  Plus,
} from '@element-plus/icons-vue'
import {ref,onMounted,reactive ,getCurrentInstance} from "vue";
import api from '@/utils/request.js';
import {formatDay, formatLoginTime} from '@/utils/date.js'
import {ElMessage, ElMessageBox, ElForm} from "element-plus";
import loginUser from "@/stores/LoginUser.js";
import router from "@/router/index.js";

let searchTime = ref(["",""])
let queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  id: null,
  nameOrCode: ""
})
let list = ref([])
let isSelectRow = ref(false)
let isAdd= ref(false);
const selectedRows = ref([]);

const { proxy } = getCurrentInstance();

let resetQueryForm=()=>{
  queryParams.value = {
    pageNum: 1,
    pageSize: 10,
    id: null,
    nameOrCode: ""
  }
}

const handleSelectionChange = (val) => {
  selectedRows.value = val;
  isSelectRow.value = selectedRows.value.length > 0;
};

let query = ()=>{
  if (searchTime.value[0]!==''){
    queryParams.value.start = formatDay(searchTime.value[0])
    queryParams.value.end = formatDay(searchTime.value[1])
  }

  api.postJson("/role/page", queryParams.value)
      .then(response => {
        if (response.code === 200) {
          list.value = response.data.list;
          queryParams.value.total = response.data.total;
        } else {
          ElMessage.error("获取角色列表失败：" + response.msg);
          list.value = [];
          queryParams.value.total = 0;
        }
      })
      .catch(error => {
        ElMessage.error("请求角色列表出错：" + error.message);
        list.value = [];
        queryParams.value.total = 0;
      })
}

const rolePageInfo = ref({
  total: 0,
  pageNum: 1,
  pageSize: 10,
  list: [],
});
let editFormVisible = ref(false)
let editForm = ref({
  rid: '', // 角色ID
  name: '',
  code: '',
  description: ''
})
let editTitle = ref('编辑')

let addPage = ()=>{
  editFormVisible.value = true
  isAdd.value = true
  editTitle.value = "新增角色"
  reset()
}

let edit = (row)=>{
  editFormVisible.value = true
  isAdd.value = false
  editTitle.value = "编辑角色"
  editForm.value ={
    rid: row.id,
    name: row.roleName,
    code: row.roleCode,
    description: row.description || ''
  }
}

function cancel() {
  editFormVisible.value = false;
  authMenuFormVisible.value = false;
  reset();
}

function reset(){
  editForm.value ={
    rid: '',
    name: '',
    code: '',
    description: ''
  }
  const editFormRef = proxy.$refs.editFormRef;
  if (editFormRef && editFormRef instanceof ElForm) {
    editFormRef.resetFields();
  }
}

function save() {
  const editFormRef = proxy.$refs.editFormRef;
  if (!editFormRef) return;

  editFormRef.validate(valid => {
    if (valid) {
      if (isAdd.value) {
        const addParams = {
          roleName: editForm.value.name,
          roleCode: editForm.value.code,
          description: editForm.value.description
        };

        api.postJson("/role/add", addParams)
            .then(response => {
              if (response.code === 200) {
                ElMessage.success("新增角色成功！");
                editFormVisible.value = false;
                query();
              } else {
                ElMessage.error("新增角色失败：" + (response.msg || "未知错误"));
              }
            })
            .catch(error => {
              ElMessage.error("新增请求出错：" + error.message);
            });
      } else {
        const updateParams = {
          id: editForm.value.rid,
          roleName: editForm.value.name,
          roleCode: editForm.value.code,
          description: editForm.value.description
        };

        api.postJson("/role/update", updateParams)
            .then(response => {
              if (response.code === 200) {
                ElMessage.success("修改角色成功！");
                editFormVisible.value = false;
                query();
              } else {
                ElMessage.error("修改角色失败：" + (response.msg || "未知错误"));
              }
            })
            .catch(error => {
              ElMessage.error("修改请求出错：" + error.message);
            });
      }
    } else {
      ElMessage.warning("请完善必填字段！");
      return false;
    }
  });
}

const deleteSelectedRows = () => {
  if (selectedRows.value.length === 0) {
    ElMessage.warning("请先选择要删除的角色！");
    return;
  }

  const idsArray = selectedRows.value.map(row => row.id);

  ElMessageBox.confirm(`是否确认删除角色编号为[${idsArray}]的数据?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    api.postJson("/role/batchDelete", idsArray)
        .then(response => {
          if (response.code === 200) {
            ElMessage.success("批量删除角色成功！");
            query();
            selectedRows.value = [];
            isSelectRow.value = false;
          } else {
            ElMessage.error("批量删除角色失败：" + (response.msg || "未知错误"));
          }
        })
        .catch(error => {
          ElMessage.error("批量删除请求出错：" + error.message);
        });
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
};

let deleteOne = (row)=>{
  ElMessageBox.confirm(`是否确认删除角色编号为[${row.id}]的数据?`, '提示', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  }).then(() => {
    api.postJson("/role/delete", row.id)
        .then(response => {
          if (response.code === 200) {
            ElMessage.success("删除角色成功！");
            query();
          } else {
            ElMessage.error("删除角色失败：" + (response.msg || "未知错误"));
          }
        })
        .catch(error => {
          ElMessage.error("删除请求出错：" + error.message);
        });
  }).catch(() => {
    ElMessage.info('已取消删除');
  })
}

// 分配菜单相关逻辑（核心修改部分）
let authMenuFormVisible = ref(false)
// 1. 打开分配菜单弹窗时，加载数据
let authMenu = (row)=>{
  authMenuFormVisible.value = true;
  // 设置当前角色信息
  editForm.value = {
    rid: row.id, // 角色ID，用于后续提交
    name: row.roleName,
    code: row.roleCode,
    description: row.description || ''
  };
  // 加载所有菜单和当前角色的菜单
  queryAllMenu(); // 先加载所有权限菜单
  queryMenuByRid(row.id); // 再加载当前角色已有的权限
}

// 2. 所有权限菜单（树形数据源）
let menuList = ref([])
// 从后端获取所有权限菜单
let queryAllMenu = ()=>{
  api.get("/permission/list")
      .then(response => {
        if (response.code === 200) {
          // 后端返回的是权限树数组，直接赋值给树形组件
          menuList.value = response.data;
        } else {
          ElMessage.error("获取所有菜单失败：" + response.msg);
          menuList.value = [];
        }
      })
      .catch(error => {
        ElMessage.error("获取所有菜单出错：" + error.message);
      });
}

// 3. 当前角色已有的权限ID（用于默认选中）
let editMenuList = ref([])
// 从后端获取当前角色的权限
let queryMenuByRid = (roleId)=>{
  api.get("/permission/listByRid",
      {id:roleId}
  )
      .then(response => {
        if (response.code === 200) {
          // 提取权限ID组成数组（后端返回的是Permission列表）
          editMenuList.value = response.data.map(perm => perm.id);
        } else {
          ElMessage.error("获取角色已有菜单失败：" + response.msg);
          editMenuList.value = [];
        }
      })
      .catch(error => {
        ElMessage.error("获取角色已有菜单出错：" + error.message);
      });
}

// 4. 树形组件引用
let treeRef = ref(null)
// 5. 提交选中的权限（核心：发送请求到role/updatemenu）
let doAuthMenu = ()=>{
  // 获取所有选中的权限ID（包括半选的父节点）
  const checkedKeys = treeRef.value.getCheckedKeys(false); // 全选节点
  const halfCheckedKeys = treeRef.value.getHalfCheckedKeys(); // 半选节点（父节点）
  const allSelectedIds = [...checkedKeys, ...halfCheckedKeys]; // 合并所有需要的权限ID

  // 构造请求参数：角色ID + 选中的权限ID数组
  const params = {
    rid: editForm.value.rid, // 角色ID
    permissionIds: allSelectedIds // 选中的权限ID列表
  };

  // 发送请求到role/updatemenu
  api.postJson("/role/updatemenu", params)
      .then(response => {
        if (response.code === 200) {
          ElMessage.success("菜单分配成功！");
          authMenuFormVisible.value = false; // 关闭弹窗
        } else {
          ElMessage.error("菜单分配失败：" + (response.msg || "未知错误"));
        }
      })
      .catch(error => {
        ElMessage.error("菜单分配请求出错：" + error.message);
      });
}

onMounted(()=>{
  resetQueryForm();
  query();
  // 初始化时无需加载菜单，打开分配弹窗时再加载
})
</script>

<template>
  <div class="app-container">
    <!-- 角色列表、新增/编辑弹窗保持不变 -->
    <el-row>
      <el-form :inline="true" :model="queryParams" class="demo-form-inline">
        <el-form-item label="ID">
          <el-input v-model="queryParams.id"  clearable />
        </el-form-item>
        <el-form-item label="角色名/权限标识">
          <el-input v-model="queryParams.nameOrCode"  clearable />
        </el-form-item>
        <el-form-item >
          <el-button type="primary" :icon="Search" @click="query">查询</el-button>
          <el-button type="primary" :icon="RefreshRight" @click="resetQueryForm">重置</el-button>
        </el-form-item>
      </el-form>
    </el-row>

    <el-row>
      <el-col>
        <el-button type="success" :icon="Plus" plain @click="addPage">新增</el-button>
        <el-button type="danger" :icon="Delete" plain @click="deleteSelectedRows" :disabled="!isSelectRow">删除</el-button>
      </el-col>
    </el-row>

    <el-row >
      <el-table
          :data="list"
          border
          stripe
          @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="roleName" label="角色名称" />
        <el-table-column prop="roleCode" label="权限标识" />
        <el-table-column prop="description" label="角色描述" />
        <el-table-column label="操作" default="scope">
          <template #default="scope" >
            <el-button type="primary" size="small" @click="edit(scope.row)" v-if="scope.row.id!==1">修改</el-button>
            <el-button type="danger" size="small" @click="deleteOne(scope.row)" v-if="scope.row.id!==1">删除</el-button>
            <el-button type="warning" size="small" @click="authMenu(scope.row)"  v-if="scope.row.id!==1">分配菜单</el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-row>

    <el-row>
      <el-col :span="24">
        <el-pagination
            v-model:current-page="queryParams.pageNum"
            v-model:page-size="queryParams.pageSize"
            :page-sizes="[5, 10, 20, 50]"
            :background="true"
            layout="total, sizes, prev, pager, next, jumper"
            :total="queryParams.total"
            @size-change="query"
            @current-change="query"
        />
      </el-col>
    </el-row>
  </div>

  <!-- 新增/编辑角色弹窗保持不变 -->
  <el-dialog v-model="editFormVisible" :title="editTitle" width="600px" append-to-body>
    <el-form
        :model="editForm"
        ref="editFormRef"
        label-width="80px"
        :rules="{
        name: [{ required: true, message: '请输入角色名', trigger: 'blur' }],
        code: [{ required: true, message: '请输入权限标识', trigger: 'blur' }],
        description: [{ max: 200, message: '角色描述不能超过200个字符', trigger: 'blur' }]
      }"
    >
      <el-row>
        <el-col :span="12">
          <el-form-item label="角色名" prop="name">
            <el-input v-model="editForm.name" placeholder="请输入角色名" maxlength="30" />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="editForm.code" placeholder="请输入权限标识（如admin）" maxlength="30" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="角色描述" prop="description">
            <el-input
                v-model="editForm.description"
                placeholder="请输入角色描述（可选）"
                maxlength="200"
                type="textarea"
                rows="3"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="save">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>

  <!-- 分配菜单弹窗（核心修改部分） -->
  <el-dialog v-model="authMenuFormVisible" title="分配菜单" width="600px" append-to-body>
    <el-form :model="editForm" ref="editFormRef"  label-width="80px">
      <el-row>
        <el-col :span="12">
          <el-form-item label="角色名" prop="name">
            <el-input v-model="editForm.name"  maxlength="30" disabled/>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item label="权限标识" prop="code">
            <el-input v-model="editForm.code"  maxlength="30" disabled/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="角色描述">
            <el-input v-model="editForm.description"  maxlength="200" disabled type="textarea" rows="2"/>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="菜单选择">
            <!-- 树形组件配置修改：匹配后端字段 -->
            <!-- 先写注释，再写标签，避免注释插入属性中间 -->
            <el-tree
                ref="treeRef"
                style="max-width: 600px; max-height: 400px; overflow-y: auto;"
                :data="menuList"
                show-checkbox
                node-key="id"
                default-expand-all
                :default-checked-keys="editMenuList"
                :props="{
    children: 'childList',
    label: 'permissionName'
  }"
            />
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="doAuthMenu">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </template>
  </el-dialog>
</template>

<style scoped>
.el-textarea__inner {
  resize: none;
}
</style>